package com.liuanbang.saro.sarodemo.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * 数字变化控件
 */
public class NumberChangeTextView extends TextView {

    //运行时长
    private final int DURATION = 1500;
    //运行标志
    private boolean isRunning = false;

    public NumberChangeTextView(Context context) {
        super(context);
    }

    public NumberChangeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public NumberChangeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 动画开始执行
     */
    public void start(NumberFormatEnum numberFormatEnum) {
        if (!isRunning) {
            //格式化
            final DecimalFormat decimalFormat = new DecimalFormat("#" + numberFormatEnum.getFormat());
            ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, new BigDecimal((getText() != null && !getText().equals("")) ? getText().toString() : numberFormatEnum.getFormat()).floatValue());
            valueAnimator.setDuration(DURATION);
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator valueAnimator) {
                    try {
                        setText(decimalFormat.format(Float.parseFloat(valueAnimator.getAnimatedValue().toString())));
                        if (valueAnimator.getAnimatedFraction() >= 1) {
                            //结束
                            isRunning = false;
                        }
                    } catch (Exception e) {
                    }
                }
            });
            valueAnimator.start();
            isRunning = true;
        }
    }
}
